import { createStore } from 'vuex'
import { RouteRecordRaw } from 'vue-router'
import { dynamicRoutes } from '@/router'
import router from '@/router'
import { fetchUserList } from '@/api'

interface UserType {
  username: string,
  password: string,
  role?: string,
  desc: string
}


export interface StateType {
  addRouter: RouteRecordRaw[],
  list: UserType[],
  total: number
}


export default createStore<StateType>({
  state: {
    // 动态路由
    addRouter: [],
    // 用于列表
    list: [],
    total: 0
  },
  mutations: {
    SET_ADD_ROUTER(state, payload) {
      state.addRouter = payload
    },
    SET_LIST(state, payload) {
      state.list = payload
    },
    SET_TOTAL(state, payload) {
      state.total = payload
    }
  },
  actions: {
    set_dynamicRouter({ commit }, role) {
      return new Promise((resolve) => {
        // 筛选角色 => 返回路由
        const addRouter = dynamicRoutes.filter(v => {
          if (role === 'admin') return true
          if (role === v.meta?.role) return true
          return false
        })
        
        //  保存动态路由到仓库
        commit('SET_ADD_ROUTER', addRouter);
        // 在router添加新的路由
        addRouter.forEach(v => {
          router.addRoute('layout', v)
        })

        resolve('')
      })
    },
    async fetch_list({ commit }, page) {
      const resp = await fetchUserList(page);

      const { data, total } = resp.data.data
      
      commit('SET_LIST', data)
      commit('SET_TOTAL', total)
    }
  },
  modules: {
  }
})
